<style>
    /* 解决 “动态添加行后滚动条不显示” 的问题 */
    .layui-layer-content {
        max-height: calc(100vh - 350px) !important; /* 最大高度限制 */
        overflow-y: auto !important; /* 溢出时显示滚动条 */
        overflow-x: hidden !important;
    }
</style>

<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form" action="" lay-filter="search-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">项目</label>
                            <div class="layui-input-inline">
                                <select name="projectId" lay-filter="projectId">
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">服务名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="hostName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn">
                                <i class="layui-icon layui-icon-search"></i>搜 索
                            </button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-reset-btn">
                                <i class="layui-icon layui-icon-refresh"></i> 重 置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <div class="layuimini-table">
            <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        </div>
    </div>
</div>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm data-add-btn" lay-event="add"> 新增</button>
    </div>
</script>

<script type="text/html" id="currentTableBar">
    <a class="layui-btn layui-btn-xs layui-btn-primary data-count-detail" lay-event="detail">集群明细</a>
    <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
</script>

<script type="text/html" id="addDialog">
    <div class="layuimini-form">
        <form class="layui-form" action="" lay-filter="add-form" id="add-form">
            <div class="layui-form-item">
                <label class="layui-form-label required">项目</label>
                <div class="layui-input-block">
                    <select name="projectId" lay-filter="projectId" lay-verify="required">
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">服务名称</label>
                <div class="layui-input-block">
                    <input type="text" name="hostName" lay-verify="required" lay-reqtext="服务名称不能为空"
                           placeholder="请输入服务名称" value="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">服务标识</label>
                <div class="layui-input-block">
                    <input type="text" name="hostSign" lay-verify="required" lay-reqtext="服务标识不能为空"
                           placeholder="请输入服务标识" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item label-wide">
                <label class="layui-form-label required">注册类型</label>
                <div class="layui-input-block">
                    <input type="radio" name="hostType" lay-filter="hostType" value="0" title="自动注册" checked>
                    <input type="radio" name="hostType" lay-filter="hostType" value="1" title="手动注册">
                </div>
            </div>
            <div class="layui-form-item label-wide">
                <label class="layui-form-label required">安全调用</label>
                <div class="layui-input-block">
                    <input type="radio" name="securityFlag" lay-filter="securityFlag" value="0" title="否" checked>
                    <input type="radio" name="securityFlag" lay-filter="securityFlag" value="1" title="是">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">accessToken</label>
                <div class="layui-input-block">
                    <div class="layui-input-wrap">
                        <input type="text" name="accessToken" disabled placeholder="" lay-affix="file" lay-filter="file" lay-options="{split: true}" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注信息</label>
                <div class="layui-input-block">
                    <textarea name="remark" class="layui-textarea" placeholder="请输入备注信息"></textarea>
                </div>
            </div>

            <fieldset class="layui-elem-field" style="margin-left: 15px">
                <legend>服务节点集群</legend>
                <div class="layui-field-box">
                    <div>
                        <div class="layui-btn-container">
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-disabled" lay-filter="addRow" disabled title="添加一行">
                                <i class="layui-icon layui-icon-add-1"></i> 添加一行
                            </button>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md12">
                            <table lay-filter="editableTable" class="layui-table" lay-size="sm">
                                <colgroup>
                                    <col width="150">
                                    <col>
                                    <col width="150">
                                    <col width="100">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th>协议</th>
                                        <th>地址</th>
                                        <th>端口</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody lay-filter="editableTableBody">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </fieldset>

            <div class="layui-form-item layui-hide">
                <button class="layui-btn" lay-submit lay-filter="addSaveBtn">保存</button>
            </div>
        </form>
    </div>
</script>


<script type="text/html" id="editDialog">
    <div class="layuimini-form">
        <form class="layui-form" action="" lay-filter="edit-form" id="edit-form">
            <div class="layui-form-item">
                <label class="layui-form-label required">项目</label>
                <div class="layui-input-block">
                    <select name="projectId" lay-filter="projectId" lay-verify="required">
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">服务名称</label>
                <div class="layui-input-block">
                    <input type="text" name="hostName" lay-verify="required" lay-reqtext="服务名称不能为空"
                           placeholder="请输入服务名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">服务标识</label>
                <div class="layui-input-block">
                    <input type="text" name="hostSign" lay-verify="required" lay-reqtext="服务标识不能为空"
                           placeholder="请输入服务标识" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item label-wide">
                <label class="layui-form-label required">注册类型</label>
                <div class="layui-input-block">
                    <input type="radio" name="hostType" lay-filter="hostType" value="0" title="自动注册" disabled>
                    <input type="radio" name="hostType" lay-filter="hostType" value="1" title="手动注册" disabled>
                </div>
            </div>
            <div class="layui-form-item label-wide">
                <label class="layui-form-label required">安全调用</label>
                <div class="layui-input-block">
                    <input type="radio" name="securityFlag" lay-filter="securityFlag"  value="0" title="否">
                    <input type="radio" name="securityFlag" lay-filter="securityFlag" value="1" title="是">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">accessToken</label>
                <div class="layui-input-block">
                    <div class="layui-input-wrap">
                        <input type="text" name="accessToken" disabled placeholder="" lay-affix="file" lay-filter="file" lay-options="{split: true}" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注信息</label>
                <div class="layui-input-block">
                    <textarea name="remark" class="layui-textarea" placeholder="请输入备注信息"></textarea>
                </div>
            </div>

            <fieldset class="layui-elem-field" style="margin-left: 15px">
                <legend>服务节点集群</legend>
                <div class="layui-field-box">
                    <div>
                        <div class="layui-btn-container">
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-disabled" lay-filter="addRow" disabled title="添加一行">
                                <i class="layui-icon layui-icon-add-1"></i> 添加一行
                            </button>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md12">
                            <table lay-filter="editableTable" class="layui-table" lay-size="sm">
                                <colgroup>
                                    <col width="150">
                                    <col>
                                    <col width="150">
                                    <col width="100">
                                </colgroup>
                                <thead>
                                <tr>
                                    <th>协议</th>
                                    <th>地址</th>
                                    <th>端口</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody lay-filter="editableTableBody">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </fieldset>

            <div class="layui-form-item layui-hide">
                <button class="layui-btn" lay-submit lay-filter="editSaveBtn">保存</button>
            </div>
        </form>
    </div>
</script>

<script>
    layui.use(['form', 'table', 'miniAjax', 'miniPage', 'layer'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
             layer = layui.layer,
            miniPage = layui.miniPage,
            miniAjax = layui.miniAjax;

        var projectList = [];
        miniAjax.get({
            url: '/project/select',
            success: function (res) {
                if (res.code == '0') {
                    projectList = res.data;
                    // 动态渲染项目下拉栏
                    $("[lay-filter='projectId']").append('<option value="">请选择</option>');
                    for (let item of projectList) {
                        $("[lay-filter='projectId']").append('<option value="' + item.id + '">' + item.projectName + '</option>');
                    }
                    form.render('select', 'search-form');
                } else {
                    layer.msg(res.msg, {time: 1000, icon: 2});
                }
            }
        });


        var currTable = table.render({
            elem: '#currentTableId',
            url: '/hosts/query',
            method: 'post',
            contentType: 'application/json',
            request: {
                pageName: 'pageNo',
                limitName: 'pageSize'
            },
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.totalCount,
                    "data": res.data.records
                };
            },
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {field: 'id', width: 50, title: 'ID', align: 'center', fixed: 'left'},
                {field: 'hostName', width: 110, title: '服务名称'},
                {
                    field: 'hostType', title: '注册类型', align: 'center', templet: function (d) {
                        if (d.hostType == '0') {
                            return `<span class="layui-badge layui-bg-blue">自动注册</span>`;
                        } else {
                            return `<span class="layui-badge layui-bg-red">手动注册</span>`;
                        }
                    }
                },
                {field: 'projectName', width: 110, title: '项目名称'},
                {field: 'hostAddrs', title: '服务节点集群', minWidth: 150},
                {field: 'createdBy', width: 75, title: '创建人'},
                {field: 'createdAt', title: '创建时间', minWidth: 150},
                {field: 'remark', width: 120, title: '备注信息'},
                {title: '操作', minWidth: 120, toolbar: '#currentTableBar', align: "center"}
            ]],
            autoSort: false,
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            // 执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                },
                where: data.field
            });
            return false;
        });

        // 监听重置操作
        form.on('submit(data-reset-btn)', function (data) {
            form.val("search-form", {
                "projectId": '',
                "hostName": ''
            });
            // 执行搜索重载
            currTable.reload({
                page: {
                    curr: 1
                },
                where: form.val("search-form")
            });
            return false;
        });

        /**
         * toolbar事件监听
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') { // 监听添加操作
                var index = layer.open({
                    title: '新增服务',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: false,
                    area: '680px', // 宽度680, 高度自适应
                    content: $('#addDialog').html(),
                    btn: ['保存', '取消'], // 按钮
                    yes: function(index, layero) {
                        layero.find("button[lay-filter='addSaveBtn']").click();  // 这一句就是点击确认按钮触发form的隐藏提交
                    },
                    success: function (layero, dIndex) {
                        // 渲染表单里的下拉框等
                        let selectHtml = '';
                        for (let item of projectList) {
                            selectHtml += '<option value="' + item.id + '">' + item.projectName + '</option>';
                        }
                        layero.find("[name='projectId']").html(selectHtml);

                        // 监听layer里面的单选框，
                        form.on('radio(hostType)', function (data) {
                            let value = data.elem.value; // 获得 radio 值
                            if (value == "0") {
                                layero.find("button[lay-filter='addRow']").addClass("layui-btn-disabled");
                                layero.find("button[lay-filter='addRow']").attr("disabled");
                            } else {
                                layero.find("button[lay-filter='addRow']").removeAttr("disabled");
                                layero.find("button[lay-filter='addRow']").removeClass("layui-btn-disabled");
                            }
                        });
                        form.on('radio(securityFlag)', function (data) {
                            let value = data.elem.value; // 获得 radio 值
                            if (value == "1") {
                                layero.find("[name='accessToken']").val(generateRandomString(32));
                            } else {
                                layero.find("[name='accessToken']").val("");
                            }
                        });
                        // 输入框点缀事件 - 搜索示例
                        form.on('input-affix(file)', function(data) {
                            let elem = data.elem; // 输入框
                            let value = elem.value; // 输入框的值
                            copyToClipboard(value)
                                .then(success => {
                                    if (success) {
                                        layer.msg('复制成功！');
                                    } else {
                                        layer.msg('复制失败，请手动复制');
                                    }
                                });
                        });

                        // 开始渲染可编辑表格
                        layero.find("button[lay-filter='addRow']").on('click', function () {
                            // 生成唯一的name属性值，避免表单冲突
                            var uniqueSuffix = new Date().valueOf();
                            var newRow = `
                                  <tr>
                                    <td data-field="protocol">
                                      <div class="table-cell-container">
                                        <select name="protocol_${uniqueSuffix}" class="layui-select" lay-verify="required">
                                          <option value="http" selected>http</option>
                                          <option value="https">https</option>
                                        </select>
                                      </div>
                                    </td>
                                    <td data-field="host">
                                      <input type="text" name="host_${uniqueSuffix}" class="layui-input" placeholder="请输入主机地址">
                                    </td>
                                    <td data-field="port">
                                      <input type="number" name="port_${uniqueSuffix}" class="layui-input" placeholder="请输入端口号">
                                    </td>
                                    <td>
                                      <button class="layui-btn layui-btn-danger layui-btn-xs deleteRow" lay-event="delete" type="button">
                                        <i class="layui-icon layui-icon-delete"></i> 删除
                                      </button>
                                    </td>
                                  </tr>
                             `;
                            layero.find("[lay-filter='editableTableBody']").append(newRow);

                            // 重新渲染表单，使新添加的下拉框生效
                            form.render('select', 'add-form');
                            // 为新添加的删除按钮绑定事件
                            bindDeleteEvents();
                        });


                        // 为可编辑表格中的删除按钮绑定事件
                        const bindDeleteEvents = () => {
                            layero.find('.deleteRow').off('click').on('click', function() {
                                var tr = $(this).closest('tr');
                                tr.remove();
                            });
                        };
                        // 获取可编辑表格的所有数据
                        const getAllData = () => {
                            var tableData = [];
                            // 遍历每一行
                            layero.find("[lay-filter='editableTableBody'] tr").each(function(index, row) {
                                var $row = $(row);
                                var rowData = {
                                    protocol: $row.find('td[data-field="protocol"] select').val(),
                                    host: $row.find('td[data-field="host"] input').val().trim(),
                                    port: $row.find('td[data-field="port"] input').val().trim()
                                };
                                tableData.push(rowData);
                            });
                            return tableData;
                        };

                        // 表单提交事件
                        form.on('submit(addSaveBtn)', function (data) {
                            // 手动注册时，需要验证服务地集群址列表不能为空
                            if (data.field.hostType == '1') {
                                let hostItems = getAllData();
                                if (!validateHostItems(hostItems)) {
                                    return false; // 校验失败，阻止提交
                                }
                                data.field.hostItems = hostItems;
                                console.log(JSON.stringify(data.field));
                            }
                            miniAjax.postJSON({
                                url: '/hosts/add',
                                data: JSON.stringify(data.field),
                                success: function (res) {
                                    if (res.code == '0') {
                                        layer.msg(res.msg, {
                                            time: 1000,
                                            icon: 1
                                        }, function () {
                                            layer.close(dIndex);
                                        });
                                    } else {
                                        layer.msg(res.msg, {time: 1000, icon: 2});
                                    }
                                }
                            });
                            return false;
                        });

                        form.render(null, 'add-form');
                    },
                    end: function (index) {
                        // 重载表格，刷新数据
                        currTable.reload();
                    }
                });
            }
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var lineData = obj.data;
            if (obj.event === 'edit') {
                var index = layer.open({
                    title: '编辑主机节点',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: false,
                    area: '680px', // 宽度680, 高度自适应
                    content: $('#editDialog').html(),
                    btn: ['保存', '取消'], // 按钮
                    yes: function(index, layero) {
                        layero.find("button[lay-filter='editSaveBtn']").click();  // 这一句就是点击确认按钮触发form的隐藏提交
                    },
                    success: function (layero, dIndex) {
                        // 渲染表单里的下拉框等
                        let selectHtml = '';
                        for (let item of projectList) {
                            selectHtml += '<option value="' + item.id + '">' + item.projectName + '</option>';
                        }
                        layero.find("[name='projectId']").html(selectHtml);
                        if (lineData.hostType == "1") {
                            layero.find("button[lay-filter='addRow']").removeAttr("disabled");
                            layero.find("button[lay-filter='addRow']").removeClass("layui-btn-disabled");
                        }

                        // 监听layer里面的单选框
                        form.on('radio(hostType)', function (data) {
                            let value = data.elem.value; // 获得 radio 值
                            if (value == "0") {
                                layero.find("button[lay-filter='addRow']").addClass("layui-btn-disabled");
                                layero.find("button[lay-filter='addRow']").attr("disabled");
                            } else {
                                layero.find("button[lay-filter='addRow']").removeAttr("disabled");
                                layero.find("button[lay-filter='addRow']").removeClass("layui-btn-disabled");
                            }
                        });
                        form.on('radio(securityFlag)', function (data) {
                            let value = data.elem.value; // 获得 radio 值
                            if (value == "1") {
                                layero.find("[name='accessToken']").val(generateRandomString(32));
                            } else {
                                layero.find("[name='accessToken']").val("");
                            }
                        });
                        // 输入框点缀事件
                        form.on('input-affix(file)', function(data) {
                            let elem = data.elem; // 输入框
                            let value = elem.value; // 输入框的值
                            copyToClipboard(value)
                                .then(success => {
                                    if (success) {
                                        layer.msg('复制成功！');
                                    } else {
                                        layer.msg('复制失败，请手动复制');
                                    }
                                });
                        });

                        // 渲染可编辑表格
                        renderTableData(lineData.hostItems, lineData.hostType);

                        layero.find("button[lay-filter='addRow']").on('click', function () {
                            // 生成唯一的name属性值，避免表单冲突
                            var uniqueSuffix = new Date().valueOf();
                            var newRow = `
                                  <tr>
                                    <td data-field="protocol">
                                      <div class="table-cell-container">
                                        <select name="protocol_${uniqueSuffix}" class="layui-select" lay-verify="required">
                                          <option value="http" selected>http</option>
                                          <option value="https">https</option>
                                        </select>
                                      </div>
                                    </td>
                                    <td data-field="host">
                                      <input type="text" name="host_${uniqueSuffix}" class="layui-input" placeholder="请输入地址">
                                    </td>
                                    <td data-field="port">
                                      <input type="number" name="port_${uniqueSuffix}" class="layui-input" placeholder="请输入端口">
                                    </td>
                                    <td>
                                      <button class="layui-btn layui-btn-danger layui-btn-xs deleteRow" lay-event="delete" type="button">
                                        <i class="layui-icon layui-icon-delete"></i> 删除
                                      </button>
                                    </td>
                                  </tr>
                             `;
                            layero.find("[lay-filter='editableTableBody']").append(newRow);

                            // 重新渲染表单，使新添加的下拉框生效
                            form.render('select', 'edit-form');
                            // 为新添加的删除按钮绑定事件
                            bindDeleteEvents();
                        });


                        // 初始化渲染表格数据
                        function renderTableData(dataList, hostType) {
                            var tableBody = layero.find("[lay-filter='editableTableBody']");
                            tableBody.empty(); // 清空表格
                            // 遍历数据列表，生成表格行
                            dataList.forEach(function(item) {
                                let row;
                                if (hostType === "0") {
                                    row = `
                                        <tr>
                                          <td data-field="protocol">${item.protocol || '-'}</td>
                                          <td data-field="host">${item.host || '-'}</td>
                                          <td data-field="port">${item.port || '-'}</td>
                                          <td></td>
                                        </tr>
                                    `;
                                } else {
                                    row = `
                                        <tr>
                                          <td data-field="protocol">
                                            <div class="table-cell-container">
                                              <select name="protocol_${item.id}" class="layui-select" lay-verify="required">
                                                <option value="http" ${item.protocol === 'http' ? 'selected' : ''}>http</option>
                                                <option value="https" ${item.protocol === 'https' ? 'selected' : ''}>https</option>
                                              </select>
                                            </div>
                                          </td>
                                          <td data-field="host">
                                            <input type="text" name="host_${item.id}" class="layui-input" placeholder="请输入地址" value="${item.host || ''}">
                                          </td>
                                          <td data-field="port">
                                            <input type="number" name="port_${item.id}" class="layui-input" placeholder="请输入端口" value="${item.port || ''}">
                                          </td>
                                          <td>
                                            <button class="layui-btn layui-btn-danger layui-btn-xs deleteRow" lay-event="delete" type="button">
                                              <i class="layui-icon layui-icon-delete"></i> 删除
                                            </button>
                                          </td>
                                        </tr>
                                    `;
                                }
                                tableBody.append(row);
                            });
                            // 重新渲染表单，使新添加的下拉框生效
                            form.render('select', 'edit-form');
                            // 绑定删除事件
                            bindDeleteEvents();
                        }

                        // 绑定删除事件
                        function bindDeleteEvents() {
                            layero.find('.deleteRow').off('click').on('click', function() {
                                var tr = $(this).closest('tr');
                                tr.remove();
                            });
                        }
                        const getAllData = () => {
                            var tableData = [];
                            // 遍历每一行
                            layero.find("[lay-filter='editableTableBody'] tr").each(function(index, row) {
                                var $row = $(row);
                                var rowData = {
                                    protocol: $row.find('td[data-field="protocol"] select').val(),
                                    host: $row.find('td[data-field="host"] input').val().trim(),
                                    port: $row.find('td[data-field="port"] input').val().trim()
                                };
                                tableData.push(rowData);
                            });
                            return tableData;
                        }

                        // 回显表单数据
                        form.val('edit-form', lineData);
                        form.render(null, 'edit-form');

                        // 表单提交事件
                        form.on('submit(editSaveBtn)', function (data) {
                            data.field.id = lineData.id;
                            if (data.field.hostType == '1') {
                                let hostItems = getAllData();
                                if (!validateHostItems(hostItems)) {
                                    return false; // 校验失败，阻止提交
                                }
                                data.field.hostItems = hostItems;
                                console.log(JSON.stringify(data.field));
                            }

                            miniAjax.postJSON({
                                url: '/hosts/edit',
                                data: JSON.stringify(data.field),
                                success: function (res) {
                                    if (res.code == '0') {
                                        layer.msg(res.msg, {
                                            time: 1000,
                                            icon: 1
                                        }, function () {
                                            layer.close(dIndex);
                                        });
                                    } else {
                                        layer.msg(res.msg, {time: 1000, icon: 2});
                                    }
                                }
                            });
                            return false;
                        });
                    },
                    end: function (index) {
                        // 重载表格，刷新数据
                        currTable.reload();
                    }
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除此服务信息吗', function (index) {
                    layer.close(index);
                    miniAjax.get({
                        url: '/hosts/delete?id=' + lineData.id,
                        success: function (res) {
                            if (res.code == '0') {
                                layer.msg(res.msg, {time: 1000, icon: 1});
                                // 重载表格，刷新数据
                                currTable.reload();
                            } else {
                                layer.msg(res.msg, {time: 1000, icon: 2});
                            }
                        }
                    });
                });
            } else if (obj.event === 'detail') {
                window.hostsId = lineData.id;
                let content = miniPage.getHrefContent('page/hostDetail.html');
                let index = layer.open({
                    title: '节点明细',
                    type: 1,
                    shade: 0.2,
                    shadeClose: false,
                    area: '780px', // 宽度780, 高度自适应
                    offset: '120px', // 手动设置垂直坐标
                    content: content,
                    success: function (layero, dIndex) {
                    },
                    end: function (index) {
                    },
                    full: function(layero, index, that) {
                        // 这样做，是为了放大缩小时，表格可以自适应大小
                        table.reload('hostDetailTableId');
                    },
                    restore: function(layero, index, that) {
                        table.reload('hostDetailTableId');
                    }
                });
            }
        });


        // 假设tableData是存储主机信息的数组（对应hostItems）
        function validateHostItems(tableData) {
            // 1. 校验最少有一行数据
            if (!tableData || tableData.length === 0) {
                layer.msg('请至少添加一条主机信息', {time: 1000, icon: 2});
                return false;
            }
            // 2. 校验每一行的字段是否完整
            for (let i = 0; i < tableData.length; i++) {
                const row = tableData[i];
                // 校验protocol非空
                if (!row.protocol || row.protocol.trim() === '') {
                    layer.msg(`第${i+1}行：协议不能为空`, {time: 1000, icon: 2});
                    return false;
                }
                // 校验host非空
                if (!row.host || row.host.trim() === '') {
                    layer.msg(`第${i+1}行：地址不能为空`, {time: 1000, icon: 2});
                    return false;
                }
                // 校验port非空且为数字（可选，根据需求添加）
                if (!row.port || row.port.trim() === '') {
                    layer.msg(`第${i+1}行：端口不能为空`, {time: 1000, icon: 2});
                    return false;
                }
                // 可选：校验端口格式为数字
                if (!/^\d+$/.test(row.port.trim())) {
                    layer.msg(`第${i+1}行：端口必须为数字`, {time: 1000, icon: 2});
                    return false;
                }
            }
            // 所有校验通过
            return true;
        }


        /**
         * 生成指定长度的随机字符串（包含数字、大小写字母、下划线）
         * @param {number} length - 生成的字符串长度，默认8位
         * @returns {string} 随机字符串
         */
        function generateRandomString(length = 8) {
            // 定义字符集：数字、大写字母、小写字母、下划线
            const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_';
            let result = '';
            // 循环生成指定长度的字符
            for (let i = 0; i < length; i++) {
                // 随机从字符集中选取一个字符
                const randomIndex = Math.floor(Math.random() * charset.length);
                result += charset[randomIndex];
            }
            return result;
        }

        /**
         * 复制文本到剪贴板
         * @param {string} value - 需要复制的文本内容
         * @returns {Promise<boolean>} - 复制成功返回 true，失败返回 false
         */
        const copyToClipboard = (value) => {
            // 方法1：使用 Clipboard API（现代浏览器推荐，更简洁）
            if (navigator.clipboard && window.isSecureContext) {
                return navigator.clipboard.writeText(value)
                    .then(() => true)
                    .catch(() => false);
            }
            // 方法2：使用传统的 textarea 模拟（兼容旧浏览器和非 HTTPS 环境）
            const textarea = document.createElement('textarea');
            textarea.value = value;
            // 隐藏文本框（不影响页面布局）
            textarea.style.position = 'absolute';
            textarea.style.left = '-9999px';
            textarea.style.opacity = '0';
            // 添加到页面并选中内容
            document.body.appendChild(textarea);
            textarea.select();
            textarea.setSelectionRange(0, value.length); // 兼容移动设备

            try {
                // 执行复制命令
                const success = document.execCommand('copy');
                document.body.removeChild(textarea); // 清理临时元素
                return Promise.resolve(success);
            } catch (err) {
                document.body.removeChild(textarea); // 出错也清理元素
                return Promise.resolve(false);
            }
        };
    });
</script>